package com.ruoyi.media.forestApi.common;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.media.forestApi.WechatMpUtilApi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@Component
@Slf4j
public class WechatMpUtilApiRequest {

    private final WechatMpUtilApi wechatMpUtilApi;

    @Value("${wxgzh.appId}")
    private String appId;

    @Value("${wxgzh.appSecret}")
    private String appSecret;


    /**
     * 获取的授权accessToken
     */
    private static String accessToken;


    /**
     * 获取公众号accessToken
     * @return
     */
    public String getAccessToken(){
        try{
            Object token =  RedisUtils.getCacheObject("WxAccessToken");
            if(token == null){
                this.resetWxToken();
            }else{
                accessToken = token.toString();
            }
        }catch (Exception e){
           log.info(e.getMessage());
        }
        return accessToken;
    }


    /**
     * 直接重新添加微信token
     */
    public void resetWxToken(){
        String res = wechatMpUtilApi.getAccessToken(appId,appSecret);
        if(res.contains("access_token")){
            accessToken = JSONObject.parseObject(res).getString("access_token");
            Long expires_in = JSONObject.parseObject(res).getLong("expires_in");
            RedisUtils.setCacheObject("WxAccessToken",accessToken, Duration.ofMinutes(expires_in - 120)); //提前2分钟失效
        }
    }



    /**
     * 获取公众号登录二维码 返回参数和
     * @return
     */
   public ArrayList<String> getScanQR() throws Exception{
           ArrayList<String> lists = new ArrayList<>();
           String params = "{\"expire_seconds\": 180, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"test\"}}}";
           String ticketStr =  wechatMpUtilApi.getScanTicket(getAccessToken(),params);
           JSONObject resData = JSONObject.parseObject(ticketStr);
           String ticket = resData.getString("ticket");
           if(ticket == null){
               this.resetWxToken();
               return null;
           }
           Map<String,Object> statusMap = new HashMap<>();
           statusMap.put("status",0);
           statusMap.put("dataMap",null);
           RedisUtils.setCacheObject(ticket,statusMap,Duration.ofMinutes(180)); //参数未扫码 存入redis
           lists.add("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=");
           lists.add(ticket);
           return lists;
   }

}
